<?php
/**
 * author  :  hation
 *  email  : 331596350@qq.com
 */

namespace App\Http\Controllers\User;


use App\Http\Controllers\CommonController;
use App\JuheHelper\JuheApi;
use App\Models\Admin;
use App\Models\FirstType;
use App\Models\Product;
use App\Models\Progress;
use App\Models\ProgressList;
use App\Models\ProgressOperatorRelation;
use App\Models\SecondType;
use DB;
use function GuzzleHttp\Psr7\build_query;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Request;

/**
 * 用户管理控制器
 * Class WorkController
 * @package App\Http\Controllers\User
 * note: 涉及用户的项目管理
 */
class WorkController extends CommonController
{
    protected $product_table = "product";
    protected $first_type_table = "first_type";
    protected $second_type_table = "second_type";
    protected $progress_list_table = "progress_list";
    protected $where = "";
    protected $pageNum = 15;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 用户工作台页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $params['user_id'] = Session::get('uid');
            $product = Progress::with(['Product', 'FirstType', 'Admin'])
                ->where($params)
                ->order()
                ->paginate($this->pageNum);
        $count = [0, 0, 0, 0];
        foreach ($product as $k => $v) {
            if ($v['first_type_id'] <= count($count)) {
                $count[$v['first_type_id'] - 1]++;
            }
        }
//        foreach($product as $k =>$v){
//            $c=$v['id'];
//            var_dump($c);
//        }
//        exit();
        $firstType = DB::table('first_type')->pluck('name');
        $data = ['product', 'count','firstType'];
//       var_dump($product);
      //dd($product);
       // dump(collect($product)->toArray());die();

        return view('user/work/index', compact($data));
    }
//    public function indexSearch(){
//        $params['user_id'] = Session::get('uid');
//        $request = Request::all();
////        dd($request);
//        $keywords="";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $product = Progress::with(['Product', 'FirstType', 'Admin'])
//            ->where($params)
//            ->order()
//            ->paginate(0);
//        //dd($product);
//        $count = [0, 0, 0, 0];
//        foreach ($product as $k => $v) {
//            if ($v['first_type_id'] <= count($count)) {
//                $count[$v['first_type_id'] - 1]++;
//            }
//        }
//       // dump($product);exit;
//        $data = ['product', 'count','keywords'];
////        dump(compact($data));exit();
//        return view('user/work/indexSearch');
//    }

    public function certainSearch()
    {
        $params = Session::get('uid');
        $content = request::all();
        //dd($content);
        $sql0="SELECT * from link_progress,link_product,link_first_type where link_progress.product_id=link_product.id and link_first_type.id=link_product.first_type_id";
        $sql=$sql0." and link_progress.user_id='".$params."'";
        //dd($sql);
        if($content['applyer']!=null)
        {
            $key=$content['applyer'];
            $sql=$sql." and link_product.applicant='".$key ."'";
        }
        if ($content['company']!=null)
        {
            $key=$content['company'];
            $sql=$sql." and link_product.company='".$key ."'";
        }
        if ($content['wordtype']!=null)
        {
            $key=$content['wordtype'];
            $sql=$sql." and link_progress.is_renew='".$key ."'";
        }
        if ($content['type']!=null)
        {
            $key=$content['type'];
            $sql=$sql." and link_first_type.id='".$key ."'";
        }
        if ($content['time']!=null)
        {
            $key=$content['time'];
            $sql=$sql." and link_progress.updated_at LIKE '".'%'.$key . '%'."'";
        }
        if ($content['state']!=null)
        {
            $key=$content['state'];
            $sql=$sql." and link_progress.state='".$key ."'";
        }
        if ($content['task']!=null)
        {
            $key=$content['task'];
            $sql=$sql." and link_product.level='".$key ."'";
        }
        if ($content['actioner']!=null)
        {
            $key=$content['actioner'];
            $sql=$sql." and link_progress.agent='".$key ."'";
        }
        $result=DB::select($sql);
        $data=['result'];
       //dd($result);
       // dd($sql);
        return view('user/work/certainSearch',compact($data));
    }
    /**
     * 任务管理页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function task()
    {
        $params['user_id'] = Session::get('uid');
            $product = Progress::with(['Product', 'FirstType', 'Admin'])
                ->where($params)
                ->latest("updated_at")
                ->paginate($this->pageNum);
        $type = ota(FirstType::all());
        //dump($product);exit;
        $data = ['product', 'type'];
        return view('user/work/task', compact($data));
    }

    /**
     * 任务管理搜索页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function taskSearch()
    {
        $params['user_id'] = Session::get('uid');
        $request = Request::all();
        $keywords="";
        if (isset($request['search'])) {
            $keywords = $request['search'];
        }
        $product = Progress::with(['Product', 'FirstType', 'Admin'])
            ->order()
            ->where($params)
            ->paginate(0);
        $type = ota(FirstType::all());
        //dd($product);
        $data = ['product', 'type','keywords'];
        return view('user/work/taskSearch', compact($data));
    }

    public function taskCertain()
    {
        $uid = Session::get('uid');
        $applicant = Request::input('applicant');
        $company = Request::input('company');
        $is_renew = Request::input('is_renew');
        $first_type = Request::input('first_type');
        $state = Request::input('state');
        $level = Request::input('level');
        //dd($applicant);
        $product = Progress::with(['Product', 'FirstType', 'Admin'])
            ->join('product','product.id','=','progress.product_id')
            ->where([
                ['product.user_id','=',$uid],
            ])
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($company, function ($query) use ($company) {
                return $query->where('product.applicant', $company);
            })
            ->when($is_renew, function ($query) use ($is_renew) {
                return $query->where('progress.is_renew', $is_renew);
            })
            ->when($first_type, function ($query) use ($first_type) {
                return $query->where('progress.first_type_id', $first_type);
            })
            ->when($state, function ($query) use ($state) {
                return $query->where('progress.state', $state);
            })
            ->when($level, function ($query) use ($level) {
                return $query->where('product.level', $level);
            })
            ->get();
        $type = ota(FirstType::all());
       // dd($product);
        $data = ['product', 'type'];
        return view('user/work/taskSearch', compact($data));
    }
    /**
     * 添加任务逻辑处理
     * @return string
     */
    public function addTask()
    {
        $date = date('Y-m-d H:i:s');
        $request = Request::all();
        // dump($request);exit;
        $params['user_id'] = Session::get('uid');
        $firstType = object_to_array(DB::table($this->first_type_table)->pluck('id'));
        $params['first_type_id'] = (int)$request['first_type'];
        $params['second_type_id'] = (int)$request['second_type'];
        $params['applicant'] = $request['apply_person'];
        $params['company'] = $request['apply_company'];
        if(empty($params['applicant'])&&empty($params['company']))
        {
            return error_return("申请人和公司必须二选一");
        }
        $params['phone'] = $request['apply_phone'];
        $params['level'] = (int)$request['mask_grade'];
        $params['is_download_notice'] = 1;
        if (!in_array($params['first_type_id'], $firstType)) {
            return error_return("类型选择错误");
        }
        $secondType = object_to_array(DB::table($this->second_type_table)
            ->where(['first_type_id' => $params['first_type_id']])
            ->pluck('id'));
        if (!in_array($params['second_type_id'], $secondType)) {
            return error_return("类型选择错误");
        }
        if (!in_array($params['level'], array_keys(config('config.product_level')))) {
            return error_return("任务等级选择错误");
        }
        if (empty($params['user_id'])) {
            return Redirect::to('user/user/login');
        }
        $params['created_at'] = $date;
        $params['updated_at'] = $date;
        $product = Product::create($params);
        //dump($params);exit;
        $re = $product->save();
        if ($re) {
            $bid=$request['business_'];
            $bb=Admin::where(['type'=>1])->pluck('id')->toArray();
            $a=0;
            if (in_array($bid,$bb)){
                $a=1;
                $admin=Admin::find($bid);
                $content="发布一项指向业务部-".$admin['real_name']."的任务";
                $progress['claim_state'] = config('config.claim_state.business');
                $progress['admin_id'] = $bid;
                $progress['agent'] = '业务部-' . $admin['real_name'];
            }else{
                $content= '发布一项任务';
                $progress['claim_state'] = config('config.claim_state.init');
            }
            $operation['product_id'] = $product['id'];
            $operation['operator_id'] = $params['user_id'];
            $operation['operator_type'] = config('config.operation_role.user');
            $operation['content'] =$content;
            $operation['operator_name'] = '用户-' . Session::get('username');
            $progress['progress_list_id'] = ProgressList::where(['second_type_id' => $params['second_type_id']])
                ->first()
                ->getKey();
            $progress['product_id'] = $product['id'];
            $progress['created_at'] = $date;
            $progress['updated_at'] = $date;
            $progress['first_type_id'] = $params['first_type_id'];
            $progress['second_type_id'] = $params['second_type_id'];
            $progress['user_id'] = $params['user_id'];
            $progress['order'] = createdNumber();
            $pro = Progress::create($progress);
            $pro->save();
            if($a==1){
                $o['progress_id'] = $pro['id'];
                $o['admin_id'] = $bid;
                $o['department_id'] = config('config.management_flag.business');
                $o['updated_at'] = $date;
                $o['created_at'] = $date;
                ProgressOperatorRelation::create($o)->save();
            }
            addOperation($operation);
            return success_return('发布成功');
        } else {
            return error_return("发布失败");
        }
    }

    /**
     * 获取产品二级分类数据
     * @return string
     */
    public function getSecondType()
    {
        $request = Request::all();
        $params['first_type_id'] = $request['id'];
        $data = ota(SecondType::where($params)->get());
        return json_return($data);
    }

    /**
     * 我的专利
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function myPatent()
    {
        return view('user/work/my_patent');
    }

    public function uploadData()
    {
        $request = Request::all();
        // $params['file']="123";
        $re1 = 0;
        $state = 0;
        $id = $request['i'];
        $pid = $request['pp'];
        //dump($request);exit;
        $item = Product::find($id);
        $item1 = Progress::find($pid);
        $uid=Session::get('uid');
        if (empty($uid)) {
            return Redirect::to('user/user/login');
        }
        if (empty($item) || empty($item1)) {
            return error_return("暂无该条记录");
        }
        $path='Uploads/resources/';
        $dir = md5($uid).'/';
        $filename = upload($path.$dir);

        if (!empty($item)){
            if(is_file($path.$item['file'])){
                unlink($path.$item['file']);
            }
        }else{
            return error_return("没有该条数据");
        }
        if(!empty($filename)){
            $item['file']=$dir.$filename;
        }else{
            return error_return('上传失败');
        }
        if (isset($item1['business_state']) && $item1['business_state'] == config('config.business_progress.first_pay_no_upload')) {
            $state = $item1['business_state'];
            $item1['business_state'] = config('config.business_progress.first_pay_upload');
            $re1 = $item1->save();
        }
        $re2 = $item->save();
        $op['product_id'] = $id;
        $op['operator_id'] = Session::get('uid');
        $op['operator_type'] = config('config.operation_role.user');
        $op['operator_name'] = "用户-" . Session::get('username');
        $op['content'] = "上传报件资料";
        if ($state != 0) {
            if ($re1 && $re2) {
                addOperation($op);
                return success_return("上传成功");
            } else {
                return error_return("上传失败");
            }
        } else {
            if ($re2) {
                addOperation($op);
                return success_return("上传成功");
            } else {
                return error_return("上传失败");
            }
        }
    }

    public function setFund($id)
    {
        if (empty(Session::get('uid'))) {
            return Redirect::to('user/user/login');
        }
        $op = [];
        $date = date('Y-m-d H:i:s');
        $item = Progress::find($id);
        if (empty($item)) {
            return error_return("暂无该条记录");
        }
        if (empty($item['price'])) {
            return error_return("业务人员还未设置款项，不能付款");
        }
        if ( $item['first']==0 &&$item['tail']==0) {
            if($item['tail_payment']=="0"){
                $item['first']=1;
                $item['tail']=1;
                $op['content'] = "支付首尾款";
            }else{
                $item['first']=1;
                $op['content'] = "支付首款";
            }
        } elseif ($item['first']==1 &&$item['tail']==0 ) {
            $item['tail'] = 1;
            $op['content'] = "支付尾款";
        } else if ($item['first']==1 &&$item['tail']==1) {
            return error_return("款项已结清,不需要支付了");
        }
        $item['updated_at'] = $date;
        $op['product_id'] = $id;
        $op['operator_id'] = Session::get('uid');
        $op['operator_type'] = config('config.operation_role.user');
        $op['operator_name'] = "用户-" . Session::get('username');
        if ($item->save()) {
            addOperation($op);
            return success_return('支付成功');
        } else {
            return error_return("支付失败");
        }
    }

    public function cancel($pid, $id)
    {
        if (empty(Session::get('uid'))) {
            return Redirect::to('user/user/login');
        }
        $op = [];
        $date = date('Y-m-d H:i:s');
        $item = Progress::find($pid);
        $item1 = Product::find($id);
        if (empty($item) || empty($item1)) {
            return error_return("暂无该条记录");
        }
        $item['is_cancel'] = config('config.mission_state_map.cancel');
        $item['updated_at'] = $date;
        $op['product_id'] = $id;
        $op['content'] = "取消任务";
        $op['operator_id'] = Session::get('uid');
        $op['operator_type'] = config('config.operation_role.user');
        $op['operator_name'] = "用户-" . Session::get('username');
        if ($item->save()) {
            addOperation($op);
            return success_return("取消成功");
        } else {
            return error_return("取消失败");
        }
    }

    public function apply($pid, $id)
    {
        if (empty(Session::get('uid'))) {
            return Redirect::to('user/user/login');
        }
        $op = [];
        $date = date('Y-m-d H:i:s');
        $item = Progress::find($pid);
        $item1 = Product::find($id);
        if (empty($item) || empty($item1)) {
            return error_return("暂无该条记录");
        }
        $item['is_cancel'] = config('config.mission_state_map.normal');
        $item['updated_at'] = $date;
        $op['product_id'] = $id;
        $op['content'] = "重新申请";
        $op['operator_id'] = Session::get('uid');
        $op['operator_type'] = config('config.operation_role.user');
        $op['operator_name'] = "用户-" . Session::get('username');
        if ($item->save()) {
            addOperation($op);
            return success_return('重新申请成功');
        } else {
            return error_return("重新申请失败");
        }
    }
    public function getBusiness(){
        return json_return(Admin::where(['type'=>1])->get());
    }


    public function juheSearchTrademarkList()
    {
        $juhe=new JuheApi(config('config.juheTrademarkAppKey'));
        $request=Request::all();
        $data['keyword']=$request['keyword'];
        $data['pageSize']=50;
        $data['pageNo']=1;
        $data['searchType']=4;
        $data['intCls']=0;
        $arr=$juhe->searchTrademarkList($data);
        return json_return($arr===false?'0':$arr);
    }
    public function juheSearchTrademarkDetail()
    {
        $juhe=new JuheApi(config('config.juheTrademarkAppKey'));
        $request=Request::all();
        $data['intCls']=(int)$request['intCls'];
        $data['regNo']=$request['regNo'];
        $trademark=$juhe->searchTrademarkDetail($data);
        if($trademark===false){
            return "暂无该专利";
        }else{
            $data=['trademark'];
            return view('user/work/indexTrademarkDetail', compact($data));
        }
    }
    public function juheSearchPatent()
    {
        $juhe=new JuheApi(config('config.juhePatentAppKey'));
        $request=Request::all();
        $data['ds']='cn';
        $data['q']=$request['q'];
        $data['p']=1;
        $data['ps']=50;
        $data['s']='relation!';
        $data['hl']=0;
        $arr=$juhe->searchPatent($data);
        return json_return($arr===false?'0':$arr);
    }
    public function juheSearchPatentInfo()
    {
        $juhe=new JuheApi(config('config.juhePatentAppKey'));
        $request=Request::all();
        $data['id']=$request['id'];
        $patent=$juhe->searchPatentInfo($data);
        if($patent===false){
            return "暂无该专利";
        }else{
            $data=['patent'];
            return view('user/work/indexPatentDetail', compact($data));
        }
    }

}
